﻿package cn.poco.pepsi.util;

import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;

public class RoundedCornerImage {
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
		Bitmap cBitmap = compress(bitmap);
		Bitmap output = Bitmap.createBitmap(cBitmap.getWidth(),

		cBitmap.getHeight(), Config.ARGB_8888);

		Canvas canvas = new Canvas(output);

		int color = 0xff424242;

		Paint paint = new Paint();

		Rect rect = new Rect(0, 0, cBitmap.getWidth(), cBitmap.getHeight());
		RectF rectF = new RectF(rect);

		float roundPx = 5;

		paint.setAntiAlias(true);

		canvas.drawARGB(0, 0, 0, 0);

		paint.setColor(color);

		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));

		canvas.drawBitmap(cBitmap, rect, rect, paint);
		cBitmap.recycle();
		cBitmap = null;
		bitmap.recycle();
		bitmap = null;
		return output;

	}

	private static Bitmap compress(Bitmap bmpOrg) {
		int width = bmpOrg.getWidth();
		int height = bmpOrg.getHeight();
		if (width != height) {
			if (width > height) {
				return Bitmap.createBitmap(bmpOrg, (width - height) / 2, 0, height, height);
			} else {
				return Bitmap.createBitmap(bmpOrg, 0, (height - width) / 2, width, width);

			}
		}
		return bmpOrg;

	}
}
